package com.linln.modules.rate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linln.common.constant.HeadImgConst;
import com.linln.common.enums.RateEnum;
import com.linln.common.vo.PageResult;
import com.linln.modules.wtpshop.service.ShopService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linln.modules.rate.mapper.RateMapper;
import com.linln.modules.rate.domain.Rate;
import com.linln.modules.rate.service.RateService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.modules.rate.service.impl
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.modules.rate.service.impl
 * @Description: TODO
 * @date Date : 2021年01月05日 14:10
 */

@Service
public class RateServiceImpl extends ServiceImpl<RateMapper, Rate> implements RateService {

    @Autowired
    private RateMapper rateMapper;

    @Autowired
    private ShopService shopService;

    @Override
    public boolean addRate(Rate rate) {
        rate.setStatus(RateEnum.WAITEXAMINE.getCode());
        return this.save(rate);
    }

    @Override
    @Transactional
    public boolean updateRateStatus(String rateId, Integer status, String shopId) {
        boolean flag = this.updateById(new Rate(rateId, status));
        if (flag && RateEnum.ADOPTEXAMINE.getCode().equals(status)) {
            Map<String, Object> map = rateMapper.selectCountScoreByShopId(shopId);
            //更新店铺评分
            long countPerson = (Long) map.get("countPerson");
            BigDecimal countScore = (BigDecimal) map.get("countScore");
            Double score = Double.parseDouble(String.format("%.1f", (countScore.doubleValue()+5) / (countPerson+1)));
            if (shopService.updateShopScore(shopId, score)) {
                return true;
            } else {
                throw new RuntimeException();
            }
        }
        return flag;
    }

    @Override
    @Transactional
    public boolean batchUpdateRateStatus(List<String> rateIds, Integer status, Set<String> shopIds) {
        int count = rateMapper.batchUpdateRateStatus(rateIds, status);

        //更新店铺评分
        if (count > 0 && RateEnum.ADOPTEXAMINE.getCode().equals(status)) {
            for (String shopId : shopIds) {
                Map<String, Object> map = rateMapper.selectCountScoreByShopId(shopId);
                long countPerson = (Long) map.get("countPerson");
                BigDecimal countScore = (BigDecimal) map.get("countScore");
                Double score = Double.parseDouble(String.format("%.1f", (countScore.doubleValue()+5) / (countPerson+1)));
                if (!shopService.updateShopScore(shopId, score)) {
                    throw new RuntimeException();
                }
            }
        }
        return count > -1;
    }

    @Override
    public PageResult<Rate> getRateList(Integer pageNum, Integer limit, String shopName, Integer status) {
        PageHelper.startPage(pageNum, limit);
        PageInfo<Rate> pageInfo = new PageInfo<>(rateMapper.selectRateList(shopName, status));
        PageResult<Rate> pageResult = new PageResult<>();
        pageResult.setData(pageInfo.getList());
        pageResult.setCount(pageInfo.getTotal());
        return pageResult;
    }

    @Value("${server.ip}")
    private String ip;

    @Override
    public Map<String, Object> getRateListByShopId(Integer pageNum, Integer limit, String shopId) {
        PageHelper.startPage(pageNum + 1, limit);
        Map<String, Object> map = new HashMap<>();
        PageInfo<Rate> pageInfo = new PageInfo<>(rateMapper.selectRateListByShopId(shopId));
        map.put("code", 200);
        List<Rate> list = pageInfo.getList();
        list.forEach(item -> {
            //判断是否是匿名用户
            if(item.getIsAnonymous()){
                //默认头像
                item.setHeadImg(ip+HeadImgConst.DEFAULTHEADIMG);
                item.setUserName("匿名用户");
            }else{
                item.setHeadImg(ip+item.getHeadImg());
            }
            //用户名为空 显示
            if(Strings.isBlank(item.getUserName())){
                item.setUserName("六甲用户");
            }
        });
        map.put("data", list);
        map.put("total", pageInfo.getTotal());
        return map;
    }


    @Override
    public boolean isRateByTicketid(String ticketId) {
        List<Rate> rateList = this.list(new QueryWrapper<Rate>().eq("ticket_id", ticketId));
        return rateList != null && rateList.size() > 0;
    }
}
